<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学生管理系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
<div class="container mx-auto px-4 py-8">
  <h1 class="text-3xl font-bold text-center mb-8 text-gray-800">学生管理系统</h1>

  <!-- 新增/编辑学生表单 -->
  <div class="bg-white rounded-lg shadow-md p-6 mb-8">
    <h2 class="text-xl font-semibold mb-4" id="formTitle">添加学生</h2>
    <form id="studentForm" class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <input type="hidden" id="studentId">
      <div>
        <label class="block text-gray-700 mb-2" for="name">姓名</label>
        <input type="text" id="name" class="w-full px-3 py-2 border rounded-md" required>
      </div>
      <div>
        <label class="block text-gray-700 mb-2" for="age">年龄</label>
        <input type="number" id="age" class="w-full px-3 py-2 border rounded-md" required>
      </div>
      <div>
        <label class="block text-gray-700 mb-2" for="gender">性别</label>
        <select id="gender" class="w-full px-3 py-2 border rounded-md" required>
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
      <div>
        <label class="block text-gray-700 mb-2" for="major">专业</label>
        <input type="text" id="major" class="w-full px-3 py-2 border rounded-md" required>
      </div>
      <div class="md:col-span-2 flex justify-end gap-4">
        <button type="button" id="resetBtn" class="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100">
          重置
        </button>
        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
          保存
        </button>
      </div>
    </form>
  </div>

  <!-- 学生列表 -->
  <div class="bg-white rounded-lg shadow-md p-6">
    <h2 class="text-xl font-semibold mb-4">学生列表</h2>
    <div class="overflow-x-auto">
      <table class="min-w-full">
        <thead>
        <tr class="bg-gray-100">
          <th class="py-3 px-4 text-left">ID</th>
          <th class="py-3 px-4 text-left">姓名</th>
          <th class="py-3 px-4 text-left">年龄</th>
          <th class="py-3 px-4 text-left">性别</th>
          <th class="py-3 px-4 text-left">专业</th>
          <th class="py-3 px-4 text-left">操作</th>
        </tr>
        </thead>
        <tbody id="studentTableBody">
        <!-- 学生数据将通过JS动态填充 -->
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
  // 后端API基础地址（实际开发中替换为真实接口地址）
  const API_BASE_URL = 'http://localhost:8080/api/students';

  // 页面加载时获取学生列表
  document.addEventListener('DOMContentLoaded', () => {
    fetchStudents();
    initEventListeners();
  });

  // 初始化事件监听
  function initEventListeners() {
    // 表单提交
    document.getElementById('studentForm').addEventListener('submit', handleFormSubmit);
    // 重置按钮
    document.getElementById('resetBtn').addEventListener('click', resetForm);
  }

  // 获取学生列表
  async function fetchStudents() {
    try {
      const response = await fetch(API_BASE_URL);
      if (!response.ok) throw new Error('获取学生列表失败');
      const students = await response.json();
      renderStudentTable(students);
    } catch (error) {
      console.error('错误:', error);
      alert('加载学生数据失败');
    }
  }

  // 渲染学生表格
  function renderStudentTable(students) {
    const tableBody = document.getElementById('studentTableBody');
    tableBody.innerHTML = '';

    students.forEach(student => {
      const row = document.createElement('tr');
      row.className = 'border-b border-gray-200';
      row.innerHTML = `
          <td class="py-3 px-4">${student.id}</td>
          <td class="py-3 px-4">${student.name}</td>
          <td class="py-3 px-4">${student.age}</td>
          <td class="py-3 px-4">${student.gender}</td>
          <td class="py-3 px-4">${student.major}</td>
          <td class="py-3 px-4">
            <button onclick="editStudent(${student.id})" class="text-blue-600 hover:text-blue-800 mr-3">
              <i class="fa fa-pencil"></i> 编辑
            </button>
            <button onclick="deleteStudent(${student.id})" class="text-red-600 hover:text-red-800">
              <i class="fa fa-trash"></i> 删除
            </button>
          </td>
        `;
      tableBody.appendChild(row);
    });
  }

  // 处理表单提交（新增或编辑）
  async function handleFormSubmit(e) {
    e.preventDefault();

    const student = {
      name: document.getElementById('name').value,
      age: parseInt(document.getElementById('age').value),
      gender: document.getElementById('gender').value,
      major: document.getElementById('major').value
    };

    const studentId = document.getElementById('studentId').value;

    try {
      if (studentId) {
        // 编辑学生（PUT请求）
        await fetch(`${API_BASE_URL}/${studentId}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(student)
        });
      } else {
        // 新增学生（POST请求）
        await fetch(API_BASE_URL, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(student)
        });
      }

      resetForm();
      fetchStudents(); // 重新加载列表
      alert(studentId ? '修改成功' : '添加成功');
    } catch (error) {
      console.error('错误:', error);
      alert('操作失败');
    }
  }

  // 编辑学生
  async function editStudent(id) {
    try {
      const response = await fetch(`${API_BASE_URL}/${id}`);
      if (!response.ok) throw new Error('获取学生信息失败');
      const student = await response.json();

      // 填充表单
      document.getElementById('studentId').value = student.id;
      document.getElementById('name').value = student.name;
      document.getElementById('age').value = student.age;
      document.getElementById('gender').value = student.gender;
      document.getElementById('major').value = student.major;
      document.getElementById('formTitle').textContent = '编辑学生';
    } catch (error) {
      console.error('错误:', error);
      alert('加载学生信息失败');
    }
  }

  // 删除学生
  async function deleteStudent(id) {
    if (!confirm('确定要删除该学生吗？')) return;

    try {
      await fetch(`${API_BASE_URL}/${id}`, { method: 'DELETE' });
      fetchStudents(); // 重新加载列表
      alert('删除成功');
    } catch (error) {
      console.error('错误:', error);
      alert('删除失败');
    }
  }

  // 重置表单
  function resetForm() {
    document.getElementById('studentForm').reset();
    document.getElementById('studentId').value = '';
    document.getElementById('formTitle').textContent = '添加学生';
  }
</script>
</body>
</html>
